package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.annotation.Client_oper;
import com.ruoyi.client.annotation.TargetJson;
import com.ruoyi.client.domain.entity.BlogComment;
import com.ruoyi.client.domain.entity.BlogUser;
import com.ruoyi.client.domain.vo.CommentVo;
import com.ruoyi.client.domain.vo.EchartsVo;
import com.ruoyi.client.eum.ClientBusinessType;
import com.ruoyi.client.service.IBlogCommentService;
import com.ruoyi.client.service.IBlogUserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.json.utils.JsonUtils;
import com.ruoyi.common.web.core.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@RestController
@RequestMapping("client/user/comment")
public class BlogCommentController extends BaseController {
    @Autowired
    IBlogCommentService commentService;
    @Autowired
    IBlogUserService userService;
    @GetMapping("addCommentNum")
    public R<List<EchartsVo>> getAddCommentNum(){
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取7天前的日期
        LocalDate sevenDaysAgo = today.minusDays(6); // 包括今天，所以减去6天
        // 获取最近7天的开始时间（7天前的 00:00:00）
        LocalDateTime startOfLastSevenDays = sevenDaysAgo.atStartOfDay();
        // 获取最近7天的结束时间（今天的 23:59:59.999999999）
        LocalDateTime endOfLastSevenDays = today.atTime(LocalTime.MAX);
        List<EchartsVo> result = commentService.addLikeNum(userId,startOfLastSevenDays,endOfLastSevenDays);
        return R.ok(result);
    }

    @PostMapping("likeComment")
    public R<CommentVo> likeComment(@RequestBody BlogComment comment){
        CommentVo blogComment = commentService.likeComment(comment);
        return R.ok(blogComment);
    }
    @GetMapping("/{id}")
    public R<List<CommentVo>> getComment(@PathVariable Long id){
        List<CommentVo> result = commentService.getComment(id);
        return R.ok(result);
    }
    /**
     * 保存评论
     * @param comment
     * @return
     */
    @PostMapping
    @Client_oper(title = "评论",clientBusinessType = ClientBusinessType.TYPE_COMMENT)
    public R<CommentVo> saveComment(@RequestBody @TargetJson BlogComment comment){
        // 设置评论人信息
        Long userId = Long.valueOf((String) StpUtil.getLoginId());
        comment.setUserId(userId);
        comment.setRelateId(comment.getTargetId());
        BlogUser user = userService.getById(userId);
        String s = JsonUtils.toJsonString(user);
        comment.setUserJson(s);
        // 保存
        CommentVo commentVo = commentService.saveComment(comment);
        commentVo.setUser(user);
        return R.ok(commentVo);
    }
}
